package com.txunda.zhuohired.aty.user.resume;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ants.theantsgo.gson.GsonUtil;
import com.ants.theantsgo.tools.AlertDialog;
import com.ants.theantsgo.util.JSONUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.txunda.zhuohired.R;
import com.txunda.zhuohired.adapter.user.resume.SocialAdapter;
import com.txunda.zhuohired.base.BaseAty;
import com.txunda.zhuohired.bean.user.resume.SocialBean;
import com.txunda.zhuohired.http.pst.ResumePst;
import com.txunda.zhuohired.util.UrlUtil;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 创建人： Txd_Cjh
 * 创建时间： 2018/3/7 16:25
 * 功能描述：社交主页
 * 联系方式：jiahuanchen@126.com
 */

public class SocialAty extends BaseAty {
    /**
     * 标题
     */
    @ViewInject(R.id.tv_layout_white_center)
    private TextView tv_layout_white_center;
    /**
     * listView
     */
    @ViewInject(R.id.lv_social)
    private ListView lv_social;
    /**
     * 社交主页
     */
    @ViewInject(R.id.et_social_http)
    private EditText et_social_http;
    /**
     * 添加
     */
    @ViewInject(R.id.iv_social_sure)
    private ImageView iv_social_sure;
    /**
     * 空数据
     */
    @ViewInject(R.id.ll_no_data)
    private LinearLayout ll_no_data;

    private SocialAdapter socialAdapter;
    private ResumePst resumePst;
    private String token = "";
    private List<SocialBean.DataBean> socialList;
    private String social_http = "";
    private String model = "UserSocial";//UserPractice.工作经历，UserEducation.教育经历，UserJob.项目经历，UserSocial.社交主页

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showStatusBar(R.id.layout_white_head);
        tv_layout_white_center.setText("社交主页");
        checkNetWorkStatus(this);
    }

    @Override
    @OnClick({R.id.iv_social_sure, R.id.tv_social_sure})
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_social_sure://添加社交主页
                social_http = et_social_http.getText().toString().trim();
                //                L.e("============", UrlUtil.isConnect(social_http) + "");
                if (UrlUtil.isConnect(social_http) == null) {
                    showErrorTip("请输入可用地址");
                    return;
                }
                resumePst.addSocial(token, social_http);
                closeKeyboard(this, iv_social_sure);
                break;
            case R.id.tv_social_sure://完成
                finish();
                break;
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.aty_social;
    }

    @Override
    protected void initialized() {
        resumePst = new ResumePst(this);
        token = application.getUserInfo().get("data");
        socialList = new ArrayList<>();
    }

    @Override
    protected void requestData() {
        initHttp();
    }

    private void initHttp() {
        resumePst.social(token);
    }

    private void initAdapter() {
        socialAdapter = new SocialAdapter(this, socialList);
        lv_social.setAdapter(socialAdapter);
        socialAdapter.SetOnClickListener(new SocialAdapter.HolderClickListener() {
            @Override
            public void onSureHolderClick(int position) {
                onShowDialog(socialList.get(position).getId());
            }
        });

    }

    private void onShowDialog(final String id) {
        new AlertDialog(this).builder().setTitle("提示").setMsg("确认删除该社交主页?")
                .setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        //                        L.e("======id======",id);
                        //                        L.e("======model======",model);
                        resumePst.delPractice(id, model);
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        }).show();
    }

    @Override
    public void onComplete(String requestUrl, String jsonStr) {
        super.onComplete(requestUrl, jsonStr);
        if (requestUrl.contains("social")) {
            //            L.e("==========social=========", jsonStr);
            SocialBean socialBean = GsonUtil.GsonToBean(jsonStr, SocialBean.class);
            socialList = socialBean.getData();
            if (socialList.size() == 0) {
                noData(2);
            } else {
                noData(1);
                initAdapter();
            }
            return;
        }
        if (requestUrl.contains("addSocial")) {
            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(jsonStr);
            showRightTip(map.get("message"));
            et_social_http.setText("");
            initHttp();
            return;
        }
        if (requestUrl.contains("delPractice")) {
            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(jsonStr);
            showRightTip(map.get("message"));
            initHttp();
            return;
        }
    }

    /**
     * @param type 1 有数据 2 无数据
     */
    private void noData(int type) {
        if (type == 1) {
            lv_social.setVisibility(View.VISIBLE);
            ll_no_data.setVisibility(View.GONE);
        } else {
            lv_social.setVisibility(View.GONE);
            ll_no_data.setVisibility(View.VISIBLE);
        }
    }

    //检查网络连接状态，Monitor network connections (Wi-Vi, GPRS, UMTS, etc.)
    public static boolean checkNetWorkStatus(Context context) {
        boolean result;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netinfo = cm.getActiveNetworkInfo();
        if (netinfo != null && netinfo.isConnected()) {
            result = true;
            Log.i("11111", "The net was connected");
        } else {
            result = false;
            Log.i("22222", "The net was bad!");
        }
        return result;
    }

    public static boolean checkURL(String url) {
        boolean value = false;
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            int code = conn.getResponseCode();
            System.out.println(">>>>>>>>>>>>>>>> " + code + " <<<<<<<<<<<<<<<<<<");
            if (code != 200) {
                value = false;
            } else {
                value = true;
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return value;
    }

}
